package com.sqx.modules.scFollow.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.TbFootprintDao;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.entity.TbFootprint;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.goods.entity.Goods;
import com.sqx.modules.goods.vo.GoodsVo;
import com.sqx.modules.scFollow.dao.ScFollowDao;
import com.sqx.modules.scFollow.entity.DateDataPair;
import com.sqx.modules.scFollow.entity.ScFollow;
import com.sqx.modules.scFollow.service.ScFollowService;
import com.sqx.modules.trends.dao.TrendsDao;
import com.sqx.modules.trends.vo.TrendsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;


@Service
public class ScFollowServiceImpl extends ServiceImpl<ScFollowDao, ScFollow> implements ScFollowService {

    @Autowired
    private TbFootprintDao footprintDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private TrendsDao trendsDao;

    @Override
    public Result updateFollow(ScFollow follow) {
        Integer count = baseMapper.selectCount(new QueryWrapper<ScFollow>()
                .eq("user_id", follow.getUserId())
                .eq("by_id", follow.getById())
                .eq("classify", follow.getClassify()));
        if (count > 0) {
            baseMapper.delete(new QueryWrapper<ScFollow>().eq("user_id", follow.getUserId())
                    .eq("by_id", follow.getById()).eq("classify", follow.getClassify()));
            if (follow.getClassify() == 1) {
                return Result.success("取消收藏成功");
            } else if (follow.getClassify() == 2) {
                return Result.success("取消想要成功");
            } else if (follow.getClassify() == 3) {
                return Result.success("取消关注成功");
            } else if (follow.getClassify() == 4) {
                return Result.success("取消动态收藏成功");
            }
        } else {
            follow.setCreateTime(LocalDateTime.now());
            baseMapper.insert(follow);
            if (follow.getClassify() == 1) {
                return Result.success("收藏成功");
            } else if (follow.getClassify() == 2) {
                return Result.success("想要成功");
            } else if (follow.getClassify() == 3) {
                return Result.success("关注成功");
            } else if (follow.getClassify() == 4) {
                return Result.success("动态收藏成功");
            }
        }
        return Result.error("操作失败");
    }


    @Override
    public Page<Goods> getFollowGoodsList(Long userId, Integer page, Integer limit, ScFollow follow) {
        Page<GoodsVo> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return baseMapper.getFollowGoodsList(pages, userId, follow);

    }

    @Override
    public Page<TrendsVo> selectByMyCollect(Long userId, Integer page, Integer limit, ScFollow follow) {
        Page<TrendsVo> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return trendsDao.selectByMyCollect(pages, userId, follow);

    }


    @Override
    public int getMyFollowCount(Long userId) {

        return baseMapper.getMyFollowCount(userId);
    }

    @Override
    public int getMyFollowGoodsCount(Long userId) {
        return baseMapper.getMyFollowGoodsCount(userId);
    }

    @Override
    public Result selectMyFootprintList(Long userId, Integer pageNum, Integer pageSize,Integer status) {
        UserEntity user = userDao.selectById(userId);
        if (user == null) {
            return Result.error("用户信息不存在，请重新登录");
        }
        PageHelper.startPage(pageNum, pageSize);
        List<TbFootprint> list = footprintDao.selectByUserId(userId,status);
        // 统计出多少人想要此件商品
        for (TbFootprint tbFootprint : list) {
            if (tbFootprint.getGoodId() == null) {
                System.out.println("Found null goodId in footprint: " + tbFootprint);
            }
            tbFootprint.setFollowCount(baseMapper.selectCount(new QueryWrapper<ScFollow>()
                    .eq("by_id", tbFootprint.getGoodId())
                    .eq("classify", 2)));
        }
        // 按照visitTime的年月日分组
        Map<LocalDate, List<TbFootprint>> groupedByDate = list.stream()
                .collect(Collectors.groupingBy(
                        tbFootprint -> tbFootprint.getVisitTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate()));

        // 创建一个列表存储结果：每个元素是一个DateDataPair对象
        List<DateDataPair> resultPairs = new ArrayList<>();

        // 遍历分组后的Map，将日期和对应的TbFootprint列表提取出来，并创建DateDataPair对象
        groupedByDate.forEach((date, footprints) -> {
            // 在每个日期组内按照goodId去重，并保留最新的记录
            Map<Long, TbFootprint> uniqueByGoodId = footprints.stream()
                    .filter(fp -> fp.getGoodId() != null)
                    .collect(Collectors.toMap(
                            TbFootprint::getGoodId,
                            fp -> fp,
                            (fp1, fp2) -> fp1.getVisitTime().compareTo(fp2.getVisitTime()) > 0 ? fp1 : fp2)); // 取visitTime较新的记录

            resultPairs.add(new DateDataPair(date, new ArrayList<>(uniqueByGoodId.values())));
        });

        // 对结果列表进行排序，确保按照年月日的倒序
        resultPairs.sort(Comparator.comparing(DateDataPair::getDate).reversed());

        // 计算 `start` 和 `end` 索引，并确保它们在 `resultPairs` 的范围内
//        int totalSize = resultPairs.size();
        // 计算总页数
//        int totalPages = (int) Math.ceil((double) resultPairs.size() / pageSize);

        int totalSize = resultPairs.size();
        int totalPages = (int) Math.ceil((double) totalSize / pageSize);
        // 检查请求的页码是否合理
        if (pageNum <= 1) {
            pageNum = 1; // 如果页码小于1，设置为第一页
        } else if (pageNum > totalPages && totalPages > 0) {
            pageNum = totalPages; // 如果页码大于总页数，设置为最后一页
        }else {
            return Result.success().put("data", new PageInfo<>(Collections.emptyList()));
        }
        int start = (pageNum - 1) * pageSize;
        int end = Math.min(start + pageSize, totalSize);
        // 分页逻辑：提取指定页码的数据
//        int start = (pageNum - 1) * pageSize;
//        int end = Math.min(start + pageSize, resultPairs.size());
        List<DateDataPair> paginatedResult = resultPairs.subList(start, end);
        PageInfo<DateDataPair> pageInfo = new PageInfo<>(paginatedResult);
        pageInfo.setTotal(footprintDao.selectCountByGoodId(userId));
        pageInfo.setPages(totalPages);
        pageInfo.setPageNum(pageNum);
        pageInfo.setPageSize(pageSize);
        // 返回结果
        return Result.success().put("data", pageInfo);
    }

    @Override
    public Result getFollowList(Long userId, Integer pageNum, Integer pageSize) {
        UserEntity user = userDao.selectById(userId);
        if (user == null) {
            return Result.error("用户信息不存在，请重新登录");
        }
        PageHelper.startPage(pageNum, pageSize);
        List<ScFollow> list = baseMapper.selectByUserId(userId);
        return Result.success().put("data", new PageInfo<>(list));
    }

    @Override
    public Result getFanList(Long userId, Integer pageNum, Integer pageSize) {
        UserEntity user = userDao.selectById(userId);
        if (user == null) {
            return Result.error("用户信息不存在，请重新登录");
        }
        PageHelper.startPage(pageNum, pageSize);
        List<ScFollow> list = baseMapper.selectByFanId(userId);
        return Result.success().put("data", new PageInfo<>(list));
    }

    @Override
    public Result selectMyFootprintLists(Long userId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<TbFootprint> list = footprintDao.selectByUserId(userId,null);
        return Result.success().put("data", new PageInfo<>(list));
    }

}
